package serializable.jdk;

import serializable.User;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;


public class Test1 {


    public static void main(String[] args) throws IOException {

        /**
         * 基于ByteBuffer的通用二进制编码与JDK序列化机制编码
         * 104 Byte : 23 Byte
         * 优劣明显，立见高下
         */

        useJDKSerializable();
        useByteBuffer();
    }


    /**
     * jdk序列化示例
     */
    private static void useJDKSerializable() throws IOException {
        User user = new User();
        user.setName("luobinjie");
        user.setCreed("I Can!");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(user);
        bos.flush();
        oos.close();
        byte[] result = bos.toByteArray();
        bos.close();

        System.out.println("The jdk serializable length is : " + result.length);
    }



    private static void useByteBuffer(){
        User user = new User();
        user.setName("luobinjie");
        user.setCreed("I Can!");

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        byte[] nameValue = user.getName().getBytes();
        byte[] creedValue = user.getCreed().getBytes();
        buffer.putInt(nameValue.length);
        buffer.put(nameValue);
        buffer.putInt(creedValue.length);
        buffer.put(creedValue);
        buffer.flip();

        byte[] result = new byte[buffer.remaining()];
        buffer.get(result);
        System.out.println("The bytebuffer length is : " + result.length);
    }

}
